//
//  EPGViewController.m
//  EPGChina
//
//  Created by CreeveLiu on 15/1/15.
//  Copyright (c) 2015年 sumavision. All rights reserved.
//

#import "EPGViewController.h"
#import "NetworkUtil.h"
#import "EPGModel.h"
#import "EPGBookingUtil.h"


#define TAG_BASE_ALERT_VIEW

@interface EPGViewController ()

@end

@implementation EPGViewController
{
    NSMutableArray      *_arrPrograms;
    NSIndexPath         *_playingIndexPath;
    NSArray             *_arrLocalNotis;
    UITableViewCell     *_selectedCell;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self reloadTableViewContent];
}

- (void)viewDidAppear:(BOOL)animated
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setupUI
{
    self.navigationItem.title = self.channel.title;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:nil
                                                                            action:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(shouldGotoEpgViewController:)
                                                 name:NOTI_SHOULD_GOTO_EPGVIEW object:nil];
}

- (void)reloadTableViewContent
{
    [SVProgressHUD show];
    self.navigationItem.title = self.channel.title;
    _arrLocalNotis = [[UIApplication sharedApplication] scheduledLocalNotifications];
    if (_arrPrograms == nil) {
        _arrPrograms = [[NSMutableArray alloc] init];
    } else {
        [_arrPrograms removeAllObjects];
    }
    [NetworkUtil getEPGWithChannelId:self.channel.channelId
                           completed:^(EPGModel *epg, NSError *error) {
                               [_arrPrograms addObjectsFromArray:epg.program];
                               [self.tableView reloadData];
                               NSIndexPath *playingIP = [self getPlayingIndexPath];
                               [self.tableView scrollToRowAtIndexPath:playingIP atScrollPosition:UITableViewScrollPositionTop animated:NO];
                               [self.refreshControl endRefreshing];
                               [SVProgressHUD dismiss];
                           }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arrPrograms.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }
    ProgramModel *program = [_arrPrograms objectAtIndex:indexPath.row];
    if ([self isProgramEnded:program]) {
        [cell.textLabel setTextColor:[UIColor darkGrayColor]];
        [cell.textLabel setFont:[UIFont systemFontOfSize:16]];
    } else if ([self isProgramStarted:program]) {
        [cell.textLabel setTextColor:[UIColor colorWithRed:0.188 green:0.514 blue:0.984 alpha:1.000]];
        [cell.textLabel setFont:[UIFont boldSystemFontOfSize:16]];
        _playingIndexPath = indexPath;
    } else {
        [cell.textLabel setTextColor:[UIColor blackColor]];
        [cell.textLabel setFont:[UIFont systemFontOfSize:16]];
    }
    
    if ([EPGBookingUtil isEPGBooked:program channelId:self.channel.channelId localNotifications:_arrLocalNotis]) {
        [cell.detailTextLabel setTextColor:[UIColor colorWithRed:0.188 green:0.514 blue:0.984 alpha:1.000]];
    } else {
        [cell.detailTextLabel setTextColor:[UIColor blackColor]];
    }
    
    [cell.textLabel setLineBreakMode:NSLineBreakByTruncatingMiddle];
    [cell.textLabel setText:program.t];
    [cell.detailTextLabel setText:program.showTime];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProgramModel *program = [_arrPrograms objectAtIndex:indexPath.row];
    _selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *programName = program.t;
    if ([self isProgramEnded:program]) {
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@\n%@", programName, NSLocalizedString(@"已播放", nil)]];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    } else if ([self isProgramPlaying:program]) {
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@\n%@", programName, NSLocalizedString(@"正在播放", nil)]];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    } else{
        if ([EPGBookingUtil isEPGBooked:program channelId:self.channel.channelId localNotifications:_arrLocalNotis]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:program.t
                                                                message:program.showTime
                                                               delegate:(id<UIAlertViewDelegate>)self
                                                      cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                                      otherButtonTitles:NSLocalizedString(@"取消预订", nil), nil];
            [alertView setTag:TAG_BASE_ALERT_VIEW + 0];
            [alertView show];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:program.t
                                                                message:program.showTime
                                                               delegate:(id<UIAlertViewDelegate>)self
                                                      cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                                      otherButtonTitles:NSLocalizedString(@"预订", nil), nil];
            [alertView setTag:TAG_BASE_ALERT_VIEW + 1];
            [alertView show];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    ProgramModel *program = [_arrPrograms objectAtIndex:self.tableView.indexPathForSelectedRow.row];
    if (buttonIndex == 1) {
        if (alertView.tag == TAG_BASE_ALERT_VIEW + 0) {
            [EPGBookingUtil bookProgram:program channel:self.channel.title channelId:self.channel.channelId];
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"已取消", nil)];
            [_selectedCell.detailTextLabel setTextColor:[UIColor blackColor]];
        } else {
            [EPGBookingUtil bookProgram:program channel:self.channel.title channelId:self.channel.channelId];
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"预订成功", nil)];
            [_selectedCell.detailTextLabel setTextColor:[UIColor colorWithRed:0.188 green:0.514 blue:0.984 alpha:1.000]];
        }
        
    }
    [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
}

- (BOOL)isProgramEnded:(ProgramModel *)program
{
    NSDate *date = [NSDate date];
    NSTimeInterval now = [date timeIntervalSince1970];
    if (program.et < now) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)isProgramPlaying:(ProgramModel *)program
{
    BOOL result = NO;
    if ([self isProgramStarted:program] == YES) {
        if ([self isProgramEnded:program] == NO) {
            result = YES;
        }
    }
    return result;
}

- (BOOL)isProgramStarted:(ProgramModel *)program
{
    NSDate *date = [NSDate date];
    NSTimeInterval now = [date timeIntervalSince1970];
    if (program.st < now) {
        return YES;
    } else {
        return NO;
    }
}

- (NSIndexPath *)getPlayingIndexPath
{
    for (ProgramModel *program in _arrPrograms) {
        NSInteger index = [_arrPrograms indexOfObject:program];
        if ([self isProgramEnded:program]) {
        } else if ([self isProgramStarted:program]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            _playingIndexPath = indexPath;
        } else {
            
        }
    }
    return _playingIndexPath;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)shouldGotoEpgViewController:(NSNotification *)noti
{
    if (self.isVisible) {
        ChannelModel *channel = [[ChannelModel alloc] init];
        channel.channelId = [noti.userInfo objectForKey:@"channelId"];
        channel.title = [noti.userInfo objectForKey:@"channelName"];
        EPGViewController *epgVC = [[EPGViewController alloc] init];
        epgVC.channel = channel;
        [self.navigationController pushViewController:epgVC animated:YES];
    }
}

@end
